% !TEX TS-program = pdflatex
% !TEX encoding = UTF-8 Unicode

% This is a simple template for a LaTeX document using the "article" class.
% See "book", "report", "letter" for other types of document.

\documentclass[11pt]{article} % use larger type; default would be 10pt

\usepackage[utf8]{inputenc} % set input encoding (not needed with XeLaTeX)

%%% Examples of Article customizations
% These packages are optional, depending whether you want the features they provide.
% See the LaTeX Companion or other references for full information.

%%% PAGE DIMENSIONS
\usepackage{geometry} % to change the page dimensions
\geometry{a4paper} % or letterpaper (US) or a5paper or....
% \geometry{margins=2in} % for example, change the margins to 2 inches all round
% \geometry{landscape} % set up the page for landscape
%   read geometry.pdf for detailed page layout information

\usepackage{graphicx} % support the \includegraphics command and options
\usepackage{float}

% \usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent

%%% PACKAGES
\usepackage{booktabs} % for much better looking tables
\usepackage{array} % for better arrays (eg matrices) in maths
%\usepackage{paralist} % very flexible & customisable lists (eg. enumerate/itemize, etc.)
\usepackage{verbatim} % adds environment for commenting out blocks of text & for better verbatim
\usepackage{subfig} % make it possible to include more than one captioned figure/table in a single float
% These packages are all incorporated in the memoir class to one degree or another...

%%% HEADERS & FOOTERS
\usepackage{fancyhdr} % This should be set AFTER setting up the page geometry
\pagestyle{fancy} % options: empty , plain , fancy
\renewcommand{\headrulewidth}{0pt} % customise the layout...
\lhead{}\chead{}\rhead{}
\lfoot{}\cfoot{\thepage}\rfoot{}

%%% SECTION TITLE APPEARANCE
%\usepackage{sectsty}
%\allsectionsfont{\sffamily\mdseries\upshape} % (See the fntguide.pdf for font help)
% (This matches ConTeXt defaults)

%%% ToC (table of contents) APPEARANCE
%\usepackage[nottoc,notlof,notlot]{tocbibind} % Put the bibliography in the ToC
%\usepackage[titles,subfigure]{tocloft} % Alter the style of the Table of Contents
%\renewcommand{\cftsecfont}{\rmfamily\mdseries\upshape}
%\renewcommand{\cftsecpagefont}{\rmfamily\mdseries\upshape} % No bold!

%%% END Article customizations

%%% The "real" document content comes below...

\title{AmiCoPyJava Technical Documentations}
\author{Sergey Karakovskiy and Nikolay Sohryakov}
%\date{} % Activate to display a given date or no date (if empty),
         % otherwise the current date is printed 

\begin{document}
\maketitle

\section{Introduction}
This \texttt{AmiCo} document covers bridging \texttt{Java} and \texttt{Python}. It uses \texttt{JNI} for the connection with \texttt{Java} and \texttt{ctypes} from standard \texttt{Python} distribution. This document contains description of bridging in direction \emph{Python Calls Java}. Platform specific issues about building the library are described in separate document named \emph{AmiCoPyJava User Guide}. Besides of bridging description this document contains description of the algorithm of the library and specifications of all functions of the library.

\section{Algorithm}
Library provides some separate functions for common usage(library initialization purposes) and two families of functions: returning an array as result and returning a value of simple type. JNI provides a separate function for each type of returned data(i.e. to take an integer as result of calling a method you need to use a \texttt{CallIntMethod}; to take a float pointing number as result you need to use a \texttt{CallFloatMethod} or \texttt{CallDoubleMethod} depend on the signature of the method). \texttt{AmiCoPyJava} also provides a separate function for each type of returned data.

To access to the methods, provided by \texttt{JNI} by type of the returned value without loss of performance has been used following pattern:
\begin{verbatim}
template<typename T>
T callMethodByType (char rType)
{
    switch (rType)
    {
        case 'Z': //boolean
            return (T) (env)->CallBooleanMethodA(...);
        case 'B': //byte
            return (T) (env)->CallByteMethodA(...);
        case 'C': //char
            return (T) (env)->CallCharMethodA(...);
        case 'S': //short
            return (T) (env)->CallShortMethodA(...);
        case 'I': //integer
            return (T) (env)->CallIntMethodA(...);
        ...
    }
}
\end{verbatim}
\texttt{rType} is a symbolic definition of the type. To determine type could be used \texttt{typeid} operator, but it is not cross-compiler and to avoid any problems with compilers we decided to pass a type is a char identifier. Every basic type has it's own char identifier. Identifiers are assigned accordingly to \texttt{JNI} identifiers:
\begin{table}[hp]
\center{
\begin{tabular}{ | c | c | c | }
	\hline
	C++ Type		&	Java Type	&	Identifier\\
	\hline
	void			&	void		&	V \\ \hline
	unsigned char	&	boolean	&	Z\\ \hline
	signed char	&	byte		&	B\\ \hline
	unsigned short	&	char		&	C\\ \hline
	short			&	short		&	S\\ \hline
	int			&	int		&	I\\ \hline
	long long		&	long		&	J\\ \hline
	float			&	float		&	F\\ \hline
	double		&	double	&	D\\ \hline
	char*			&	String	&	Ljava/lang/String\\ \hline
	dynamic array	&	array		&	[$<$TypeID$>$\\
	\hline
\end{tabular}
}
\end{table}
Now let's what happens when does \texttt{call<Type>Method} function of the \texttt{AmiCo} library invoked. You can see a call stack on the Figure~\ref{fig:callTypeMethod}.
\begin{figure}[H]
	\centering
		\includegraphics[scale=1]{callTypeMethod.png}
	\caption{Call stack of the \texttt{call$<$Type$>$Method} function}
	\label{fig:callTypeMethod}	
\end{figure}
When does \texttt{call<Type>Method} function called happens following: we take a signature of the method to be called by his \texttt{ID} passed as argument of the function. Then template of the function \texttt{callTMethod} for type \texttt{Type} invoked (e.g. if function \texttt{call<Type>Method} is \texttt{callIntMethod} then \texttt{callTMethod<int> invoked}). Function \texttt{callTMethod} creates an array of arguments to be passed in to the \texttt{Java} method from variable arguments list and calls \texttt{callMethodByType} function template for type \texttt{Type}. Than \texttt{callMethodByType} calls one of \texttt{JNI Call<Type>Method} functions family depend on the type of the return value. This template instantiated for \texttt{jobject} and \texttt{string} cause of specialized processing of this types.

Let's see how does it works on concrete example. Assume that \texttt{Type = int} and \texttt{call{Type}Method} is \texttt{callIntMethod}. Call stack for this function is shown on the Figure~\ref{fig:callIntMethod}.
\begin{figure}[H]
	\centering
		\includegraphics[scale=1]{callIntMethod.png}
	\caption{Call stack of the \texttt{callIntMethod} function}
	\label{fig:callIntMethod}	
\end{figure}
I think that everything is clear and doesn't need in explanation.

Another one family of the functions is \texttt{call<Type>ArrayMethod}. Return value of each function from this family is a \texttt{Python} tuple. You can see a call stack on the Figure~\ref{fig:callTypeArrayMethod}.
\begin{figure}[H]
	\centering
		\includegraphics[scale=1]{callTypeArrayMethod.png}
	\caption{Call stack of the \texttt{call$<$Type$>$ArrayMethod} function}
	\label{fig:callTypeArrayMethod}	
\end{figure}
Algorithm of this routine differs from \texttt{call<Type>Method}. It consists of two common parts: performing appropriate to the type method of the \texttt{JNI} and converting result to the \texttt{Python} tuple. Workflow of the first part is described in previous section for \texttt{call<Type>Method}: as result of performing a \texttt{JNI} method we have a \texttt{jobject} represented as \texttt{jarray} of initial for \texttt{call<Type>MethodArray} type(e.g. jintArray, jfloatArray). The next step is to convert jarray in to a \texttt{Python} tuple. There are two functions templates and one function from the \texttt{Python Framework}. First is \texttt{ConvertJavaArrayToPythonArray}. This function creates a new \texttt{tuple(PyObject)} and for each element of the \texttt{Java} array calls \texttt{PyObject\_FromJobject} to convert \texttt{Java} object to \texttt{Python} object and puts each object in to a tuple. This function (\texttt{PyObject\_FromJobject}) calls \texttt{PyInt\_FromLong} for types: \texttt{Boolean, Byte, Char, Short, Integer}; \texttt{PyLong\_FromLong} for \texttt{long} type. Function \texttt{convertJavaArrayToPythonArray} is instantiated for \texttt{<jfloatArray, jfloat>}, \texttt{<jdoubleArray, jdouble>} and \texttt{<jobjectArray, jobject>}(string is not a basic object). Template instantiated for this objects cause of converting of this types differs from another(see source code for details).

\section{Custom code}
How to improve performance of the library for your application.

\end{document}
